package com.zuihai.app.mvp.ui.activity.detail;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseApplication;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.widget.imageloader.ImageLoader;
import com.jess.arms.widget.imageloader.glide.GlideImageConfig;
import com.lcodecore.tkrefreshlayout.utils.DensityUtil;
import com.zuihai.app.R;
import com.zuihai.app.di.component.DaggerDetailComponent;
import com.zuihai.app.di.module.DetailModule;
import com.zuihai.app.mvp.constant.ReleaseConstant;
import com.zuihai.app.mvp.contract.DetailContract;
import com.zuihai.app.mvp.model.entity.Detail;
import com.zuihai.app.mvp.model.entity.mainhome.KPLogoBean;
import com.zuihai.app.mvp.presenter.DetailPresenter;
import com.zuihai.app.mvp.ui.activity.base.ToolBarBaseDetailFragment;
import com.zuihai.app.mvp.ui.adapter.DetailLabelAdapter;
import com.zuihai.app.mvp.ui.dialog.OneButtonDialog;
import com.zuihai.app.mvp.ui.dialog.ReleaseLoadingDialog;
import com.zuihai.app.mvp.ui.utils.AccountHelper;
import com.zuihai.app.mvp.ui.utils.DividerGridItemDecoration;
import com.zuihai.app.mvp.ui.utils.MJavascriptInterface;
import com.zuihai.app.mvp.ui.utils.MyUtils;
import com.zuihai.app.mvp.ui.utils.StringUtils;
import com.zuihai.app.mvp.ui.widget.Html5WebView;
import com.zuihai.app.mvp.ui.widget.MultiStateView;
import com.zuihai.app.mvp.ui.widget.MyToast;
import com.zuihai.app.mvp.ui.widget.comment.BottomSheetPictureTwoBar;
import com.tbruyelle.rxpermissions.RxPermissions;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.simple.eventbus.Subscriber;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;


/**
 * Created by Administrator on 2017/5/19 0019.
 */

public abstract class DetailFragment extends ToolBarBaseDetailFragment<DetailPresenter>
        implements DetailContract.View {
    private BottomSheetPictureTwoBar bottomComment;
    private BottomSheetPictureTwoBar bottomChildComment;
    @BindView(R.id.msv_layout)
    MultiStateView mMsvLayout;
    protected ReleaseLoadingDialog mLoadingDialog;
    private boolean isFather;
    @BindView(R.id.web_view)
    Html5WebView mWebView;
    @BindView(R.id.iv_ad)
    ImageView mAdView;
    @BindView(R.id.recommend_recycler)
    RecyclerView mRecommendRecycler;
    @BindView(R.id.comment_recycler)
    RecyclerView mCommentRecycler;
    @BindView(R.id.label_recycler)
    RecyclerView mLableRecycler;
    @BindView(R.id.scroll_view)
    ScrollView mScrollView;
    @BindView(R.id.comment_layout)
    FrameLayout mCommentLayout;
    @BindView(R.id.iv_favour_hint)
    ImageView mFavourHint;
    @BindView(R.id.iv_share_hint)
    ImageView mShareHint; //所有红包都用这个提示
    protected Detail mDetail;
    @BindView(R.id.fl_empty)
    FrameLayout flEmpty;
    private String[] imageUrls;
    @BindView(R.id.ll_getheigt)
    LinearLayout getLinearLayout;
    @BindView(R.id.content_layout)
    LinearLayout getAllLinearLayout;
    @BindView(R.id.ll_details_bottom)
    LinearLayout getLinearLayoutRecycle;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    boolean isFirstComment=false;

    private Detail.Comment mCommentData;
    //图片加载
    protected ImageLoader mImageLoader;

    protected RxPermissions mPermissions;

    private RxErrorHandler rxErrorHandler;




    protected BaseApplication mApplication;



    private RecyclerView mRecyclerView;

    private String mHuifuPicture = "";

    private String mPicture = "";

    private String url;

    private int scrollInt = 0; //记录上次滑动的位置

    private boolean tag;
    private String mAdUrl;
    private String mTiaomuId;
    private Timer timer;

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    update();
                    break;
                case 2:
                    // LogUtils.e("notfiy");
                    //mAdapter.notifyDataSetChanged();
            }
            super.handleMessage(msg);
        }

        void update() {
            //刷新msg的内容
            if (mShareHint!=null){
                mShareHint.setVisibility(View.GONE);
            }
        }
    };

    @Override
    public void showReplyLoading() {
        mLoadingDialog.show();
        mLoadingDialog.setCancelable(false);
    }

    @Override
    public void hideReplyLoading() {
        mLoadingDialog.dismiss();
        LogUtils.e("hideReplyLoading");
    }


    @Override
    public void judgeEmptyView() {

    }

    @Override
    public void haveComment(Detail.Comment data, int position) {
        if (AccountHelper.getInstance().isLogin()) {
            isFather = false;
            //由于每次点击都要最新的 所以屏蔽
            /*if (bottomChildComment==null){
                bottomChildComment = BottomSheetPictureTwoBar.delegation(getContext());
            }*/
            bottomChildComment = BottomSheetPictureTwoBar.delegation(getContext());
            bottomChildComment.show("回复"+data.userName);
     ;
        } else {

        }
    }


    private boolean allowLoad=true;
    //加载评论监听
    private BaseQuickAdapter.RequestLoadMoreListener mLoadMoreListener = new BaseQuickAdapter.RequestLoadMoreListener() {
        @Override
        public void onLoadMoreRequested() {
            LogUtils.e("allowLoad："+allowLoad);
            if (allowLoad){
                requestComment();
               // allowLoad=false;
            }

        }
    };

    @Override
    public void allowLoadComment() {
        allowLoad=true;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerDetailComponent
                .builder()
                .appComponent(appComponent)
                .detailModule(new DetailModule(this))
                .build()
                .inject(this);
        mImageLoader = appComponent.imageLoader();
        mPermissions = new RxPermissions(getActivity());
    }

    @Override
    protected void initData() {
        super.initData();
        timer = new Timer();
        mApplication= (BaseApplication) getActivity().getApplication();
        rxErrorHandler =mApplication.getAppComponent().rxErrorHandler();
        mFavourHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFavourHint.setVisibility(View.GONE);
            }
        });
        mShareHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mShareHint.setVisibility(View.GONE);
            }
        });
        LogUtils.e("is Scroll" + MyUtils.isScroll);

        mLoadingDialog = new ReleaseLoadingDialog(getContext());



        mWebView.setProgressChangedListener(new Html5WebView.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(int progress) {
                if (mScrollView != null) {
                    //  mScrollView.setVisibility(progress == 100 ? View.VISIBLE : View.GONE);
                }
            }
        });
        requestData();
    }


    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    public void showLoading() {
        mMsvLayout.setViewState(MultiStateView.VIEW_STATE_LOADING);
    }

    @Override
    public void hideLoading() {
        mMsvLayout.setViewState(MultiStateView.VIEW_STATE_CONTENT);
    }

    @Override
    public void showCollectMessage(String collectMessage) {
        MyToast.showSuccess(collectMessage);
    }

    @Override
    public void showFocusMessage(String collectMessage) {
        MyToast.showSuccess(collectMessage);
    }

    @Override
    public void showDeleteMessage(String deleteMessage) {

        MyToast.showSuccess(deleteMessage);
    }

    @Override
    public void intentMessage(Detail.Comment data) {


    }

    @Override
    public void showReplyIntentMessage(String data) {


    }



    @Override
    public void showReplyMessage(String data) {
        MyToast.showSuccess(data);
        if (mCommentData != null) {
            //start(DetailCommentInfoFragment.newInstance(mCommentData));
        }


    }

    private  OneButtonDialog dianzanDialog;

    @Override
    public void showToast(String msg) {
        MyToast.showSuccess(msg+"");
    }

    @Override
    public void showMessage(String message) {
        if (!TextUtils.isEmpty(message)) {
            if (!mDetail.haveDianzanHongbao) {

                if (!message.equals("点赞成功")){
                    dianzanDialog=new OneButtonDialog.Build(getActivity())
                            .setConfirmListener(new OneButtonDialog.OnConfirmListener() {
                                @Override
                                public void onClick(OneButtonDialog dialog, View v) {
                                    dianzanDialog.dismiss();
                                }
                            })
                            .setLogoResuorce(R.mipmap.zhanwei)
                            .setBottonText("知道了")
                            .setTextResource(message)
                            .create();
                    dianzanDialog.show();
                }else {
                    MyToast.showSuccess(message);
                }
            } else {
                 dianzanDialog=new OneButtonDialog.Build(getActivity())
                        .setConfirmListener(new OneButtonDialog.OnConfirmListener() {
                            @Override
                            public void onClick(OneButtonDialog dialog, View v) {
                                dianzanDialog.dismiss();
                            }
                        })
                        .setLogoResuorce(R.mipmap.zhanwei)
                        .setBottonText("知道了")
                        .setTextResource(message)
                        .create();
                dianzanDialog.show();
            }
        }
    }

    @Override
    public void showErrorMessage(String message) {
        OneButtonDialog errorDialog=new OneButtonDialog.Build(getActivity())
                .setConfirmListener(new OneButtonDialog.OnConfirmListener() {
                    @Override
                    public void onClick(OneButtonDialog dialog, View v) {
                        dialog.dismiss();
                    }
                })
                .setLogoResuorce(R.mipmap.zhanwei)
                .setBottonText("知道了")
                .setTextResource(message)
                .create();
        errorDialog.show();
    }

    @Override
    public void showFavourMessage(String data) {
        if (!TextUtils.isEmpty(data)) {
            MyToast.showSuccess(data);
        }
    }

    @Override
    public void showShareMessage(String message) {
        if (!TextUtils.isEmpty(message)) {
            MyToast.showSuccess(message);
        }
    }

    @Override
    public void showEmpty(String content) {
        mMsvLayout.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        tvEmpty.setText(content+"");
    }

    @Override
    public void showError(Throwable e) {
        mMsvLayout.setViewState(MultiStateView.VIEW_STATE_ERROR);
    }

    //隐藏未评论以及 回收评论图片功能
    @Override
    public void visibleFramelayout() {
        flEmpty.setVisibility(View.GONE);

        // mCommentRecycler.setVisibility(View.VISIBLE);
    }

    @Override
    public void fillContent(Detail detail) {
        mDetail = detail;
        imageUrls = StringUtils.returnImageUrlsFromHtml(detail.content);
        mWebView.addJavascriptInterface(new MJavascriptInterface(getActivity(), imageUrls), "imagelistener");
        //内容
        String text = detail.content;//网页获取的html文本
        Document mDocument = Jsoup.parse(text);
        Elements imageSrc = mDocument.select("img[src]");
        for (Element element : imageSrc) {
            element.addClass("lazy");
            String imgUrl = element.attr("src");

            String strWidth = element.attr("width"); //获取服务器返回放的 宽高
            String strHeight = element.attr("height");
            //LogUtils.e("width : " +strWidth);
            //LogUtils.e("height : " +strHeight);
            double width = Double.parseDouble(strWidth); //将宽高转换为double类型
            double height = Double.parseDouble(strHeight);
            double widthDp = DensityUtil.           //将宽高转换成 dp
                    px2dp(getActivity(), (float) width);
            double heightDp = DensityUtil.
                    px2dp(getActivity(), (float) height);
            double n = widthDp / heightDp;   //宽高比  宽度 / 高度
            WindowManager wm = (WindowManager) getContext()
                    .getSystemService(Context.WINDOW_SERVICE);
            double widthScreen = wm.getDefaultDisplay().getWidth();
            int wScreenDP = DensityUtil.   //当前屏幕的宽度dp
                    px2dp(getActivity(), (float) widthScreen)-35; //数字变低实际越高 变高越低
            LogUtils.e("screen==== "+wScreenDP);
            double calculateHeight = wScreenDP / n;
            element.attr("src", "file:///android_asset/ic_picture_default_four.png");
            element.attr("width", wScreenDP + "").attr("height", calculateHeight + "");
            element.attr("data-original", imgUrl);
        }
        text = mDocument.toString();
        mWebView.setupBody(text);
        //没有评论就隐藏评论列表

        if (detail.comments.isEmpty()) {
            flEmpty.setVisibility(View.VISIBLE);
            // mCommentRecycler.setVisibility(View.GONE);
        } else {
            flEmpty.setVisibility(View.GONE);
        }
        //没有推荐就隐藏推荐列表
        if (detail.recommends.isEmpty()) {
            mRecommendRecycler.setVisibility(View.GONE);
        }
        //没有标签就隐藏标签列表
        if (detail.label.isEmpty()) {
            mLableRecycler.setVisibility(View.GONE);

        } else {
            if (detail.label.get(0).text.length() == 0) {
                mLableRecycler.setVisibility(View.GONE);
            }
        }
        mFavourHint.setVisibility(detail.haveDianzanHongbao ? View.VISIBLE : View.GONE);
        //mShareHint.setVisibility(detail.haveFenxiangHongbao ? View.VISIBLE : View.GONE);
        if (detail.haveDianzanHongbao&&detail.haveFenxiangHongbao){
            mShareHint.setImageResource(R.mipmap.prompt_two);
            mShareHint.setVisibility(View.VISIBLE);
        }else if (detail.haveFenxiangHongbao){
            mShareHint.setImageResource(R.mipmap.prompt_share);
            mShareHint.setVisibility(View.VISIBLE);
        }else if (detail.haveDianzanHongbao){
            mShareHint.setImageResource(R.mipmap.prompt_praise);
            mShareHint.setVisibility(View.VISIBLE);
        }else {
            mShareHint.setVisibility(View.GONE);
        }

        /*  //是否显示点赞红包提示
        if (detail.isFavour) {
            mFavourHint.setVisibility(View.VISIBLE);
        }*/
        TimerTask taskAdapter = new TimerTask() {
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        timer.schedule(taskAdapter, 3000);
    }

    /**
     * 跳转评论列表
     */
    @OnClick(R.id.comment_layout)
    public void onCommentList() {
        tag = mCommentLayout.getTag() == null ? true : (boolean) mCommentLayout.getTag();

        //  LogUtils.e("webView getY : " + mWebView.getY());
        //LogUtils.e("webView getHeight : " + mWebView.getHeight());
        mScrollView.smoothScrollTo(0, tag ?
                getLinearLayout.getMeasuredHeight() +
                        getLinearLayoutRecycle.getMeasuredHeight() : scrollInt);
        mCommentLayout.setTag(!tag);


    }

    @Override
    public void firstComment(boolean isFirst) {
        isFirstComment=isFirst;


    }

    /**
     * 评论之后跳转评论列表
     */
    public void onPinglunCommentList() {
        //LogUtils.e("webView getY : " + mWebView.getY());
        //LogUtils.e("webView getHeight : " + mWebView.getHeight());
        if (isFirstComment){
            LogUtils.e("onPinglunCommentList  第一次评论");
            mScrollView.smoothScrollTo(0, getLinearLayout.getMeasuredHeight() +
                    getLinearLayoutRecycle.getMeasuredHeight()+mCommentRecycler.getMeasuredHeight());

        }else {
            LogUtils.e("onPinglunCommentList  其他评论");
            mScrollView.smoothScrollTo(0, getLinearLayout.getMeasuredHeight() +
                    getLinearLayoutRecycle.getMeasuredHeight());
        }

    }

    /**
     * 收藏
     *
     * @param view
     */
    @OnClick(R.id.iv_collect)
    public void onCollect(View view) {
    }

    /**
     * 分享
     *
     * @param v
     */
    @OnClick(R.id.iv_share)
    public void onShare(View v) {
        showShare();
       /* PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {
                showShare();
            }

            @Override
            public void onRequestPermisstionFailure() {

            }
        }, mPermissions);*/
    }

    @Override
    public void adContent(KPLogoBean bean) {

    }

    /**
     * 广告
     *
     * @param url
     */
    @Override
    public void fillAd(String url) {
        mImageLoader.loadImage(getActivity(), GlideImageConfig.builder()
                .url(url)
                .imageView(mAdView)
                .placeholder(R.mipmap.position_rectangle_big)
                .build());
        mAdView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }





    @Override
    public void bindLabelRecycler(DetailLabelAdapter adapter) {
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mLableRecycler.setNestedScrollingEnabled(false);
        mLableRecycler.setHasFixedSize(false);
        mLableRecycler.setLayoutManager(layoutManager);
        adapter.setOnItemClickListener(mLabelClickListener);
        mLableRecycler.setAdapter(adapter);
        DividerGridItemDecoration itemDecoration = new DividerGridItemDecoration(getContext(), R.drawable.money_divider_shape);
        mLableRecycler.addItemDecoration(itemDecoration);
    }

    @Override
    public void finishLoadComment() {

        LogUtils.e("加载完成了  没有更多了");
    }



    //  Html.fromHtml(mDetail.content).toString();
    /**
     * 分享
     */
    public void showShare() {
        if (mDetail == null) {
            return;
        }
        url = mDetail.shareUrl;
        LogUtils.e("分享" + url);
        String picturlUrl = null;
        if (mDetail.pictures.size() > 0) {
            picturlUrl = mDetail.pictures.get(0).pictureUrl;
        }

    }

    /**
     * 加载网络图片
     *
     * @param path
     * @param target
     */
    public void loaderImage(String path, ImageView target) {
        if (TextUtils.isEmpty(path)) return;
        mImageLoader.loadImage(mActivity, GlideImageConfig
                .builder()
                .url(path)
                .imageView(target)
                .placeholder(R.mipmap.position_rectangle_big)
                .build());
    }

    /**
     * 加载头像网络图片
     *
     * @param path
     * @param target
     */
    public void loaderHeadImage(String path, ImageView target) {
        if (TextUtils.isEmpty(path)) return;
        mImageLoader.loadImage(mActivity, GlideImageConfig
                .builder()
                .url(path)
                .imageView(target)
                .placeholder(R.mipmap.tab_complete)
                .build());
    }

    /**
     * 请求详情数据
     */
    protected abstract void requestData();

    /**
     * 请求评论
     */
    protected abstract void requestComment();

    protected void requestInform(String inform) {
        mPresenter.requestInform(mDetail.id, inform, mDetail.type);
    }


    /**
     * 分享红包
     */
    protected abstract void shareLuckyMoney();

    @Override
    public void scrollComment() {
        onPinglunCommentList();
    }

    /**
     * 推荐内容
     *
     * @param adapter
     * @param view
     * @param position
     */
    protected abstract void onRecommetClick(BaseQuickAdapter adapter, View view, int position);



    //文章标题图片
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ReleaseConstant.REQUEST_CODE_PICK_IMAGE:
                if (resultCode == RESULT_OK) {

                }
                break;
        }
    }

    //注解跳转详情
    @Subscriber(tag = "intentcommentinfo")
    public void intentcommentinfo(String Images) {

    }

    //推荐内容点击回调
    private BaseQuickAdapter.OnItemClickListener mRecommentClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            onRecommetClick(adapter, view, position);
        }
    };

    //标签点击回调
    private BaseQuickAdapter.OnItemClickListener mLabelClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        }
    };

    @Override
    public void onDestroy() {
        if (timer != null) {// 停止timer
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

    @org.simple.eventbus.Subscriber(tag = "refreshlist")
    public void refreshList(String pinglunId) {
       /* for (int i = 0; i < mCommentAdapter.getData().size(); i++) {
            if (mCommentAdapter.getData().get(i).id.equals(pinglunId)){
                mCommentAdapter.remove(i);
            }
        }
        mCommentAdapter.notifyDataSetChanged();*/

    }
    @Subscriber(tag = "detailcommentinfo")
    public void detailcommentinfo(String pinglunId) {

        judgeEmptyView();
    }


    @Override
    public void intentTuijian() {

    }
}
